cmake_minimum_required (VERSION 2.6)
project (coroutine)

# Display verbose info
set (CMAKE_VERBOSE_MAKEFILE ON)

# Setting up version numbers
set (VERSION_MAJOR 1)
set (VERSION_MINOR 0)

if (UNIX)
    # Select coroutine context.
    set(USE_UCONTEXT 1)
    message (STATUS "Use ucontext context")

    # Select the polling method
    set (POLLER "" CACHE STRING "Choose polling method. valid values are kqueue, epoll or poll [default=autodetect]")
    include (CheckFunctionExists)
    if (POLLER STREQUAL "")
        set (CMAKE_REQUIRED_INCLUDES sys/event.h)
        check_function_exists (kqueue HAVE_KQUEUE)
        set (CMAKE_REQUIRED_INCLUDES)
        if (HAVE_KQUEUE)
            set (POLLER "kqueue")
        endif ()
    endif ()
    if (POLLER STREQUAL "")
        set (CMAKE_REQUIRED_INCLUDES sys/epoll.h)
        check_function_exists (epoll_create HAVE_EPOLL)
        set (CMAKE_REQUIRED_INCLUDES)
        if (HAVE_EPOLL)
            set (POLLER "epoll")
        endif ()
    endif ()
    if (POLLER STREQUAL "")
        set (CMAKE_REQUIRED_INCLUDES sys/poll.h)
        check_function_exists (poll HAVE_POLL)
        set (CMAKE_REQUIRED_INCLUDES)
        if (HAVE_POLL)
            set (POLLER "poll")
        else ()
            message (FATAL_ERROR, "Could not autodetect polling method")
        endif ()
    endif ()
    message (STATUS "Detected ${POLLER} polling method")
    string (TOUPPER ${POLLER} UPPER_POLLER)
    set (USE_${UPPER_POLLER} 1)

elseif (WIN32)
    # Select coroutine context.
    set(USE_FIBER 1)
    message (STATUS "Use fiber context")
endif ()

# Configuration files
configure_file (
    ${CMAKE_SOURCE_DIR}/config.h.in
    ${PROJECT_BINARY_DIR}/config.h
)

set (CMAKE_SOURCE_DIR .)
if (UNIX)
	set (CMAKE_C_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb ") # –pg
    set (CMAKE_C_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall ")
elseif (WIN32)
    add_definitions(-D_CRT_SECURE_NO_WARNINGS)
endif ()

# Header & Source files
include_directories (
    ${CMAKE_SOURCE_DIR}/include
    ${CMAKE_SOURCE_DIR}/src
    ${PROJECT_BINARY_DIR}
)
aux_source_directory(${CMAKE_SOURCE_DIR}/src coroutine_SRCS)

if (UNIX)
    include_directories(${CMAKE_SOURCE_DIR}/src/unix)
    aux_source_directory(${CMAKE_SOURCE_DIR}/src/unix coroutine_SRCS)
elseif (WIN32)
    include_directories(${CMAKE_SOURCE_DIR}/src/win32)
    aux_source_directory(${CMAKE_SOURCE_DIR}/src/win32 coroutine_SRCS)
endif ()

# The executable
add_executable(coroutine ${coroutine_SRCS})

# The Install targets
set (CMAKE_INSTALL_PREFIX "${PROJECT_BINARY_DIR}/lib")
install (TARGETS coroutine DESTINATION bin)

# Tests
include (CTest)
add_test (coroutine_runs coroutine)
add_test (coroutine_arg25 coroutine 123)
set_tests_properties (coroutine_arg25
    PROPERTIES PASS_REGULAR_EXPRESSION "arg\\[1\\]=123")
